import { setToken, removeToken, setSession, clearSession } from '@/util/auth'
import { setStore, getStore } from '@/util/store'
import { isURL, validatenull } from '@/util/validate'
import { deepClone } from '@/util/util'
import webiste from '@/config/website'
import menuData from "@/router/common/menu.js";
import menuUnique from "@/router/common/menuUnique.js";
import { loginByUsername, getUserInfo, logout, refeshToken } from '@/api/user'


// 通过权限的
let dataList = []

function addPath(ele, first) {
  const menu = webiste.menu;
  const propsConfig = menu.props;
  const propsDefault = {
    label: propsConfig.label || 'label',
    path: propsConfig.path || 'path',
    icon: propsConfig.icon || 'icon',
    children: propsConfig.children || 'children'
  }
  // 权限处理
  if (first && dataList && dataList.indexOf(ele.unique) == -1) {
    return true
  }

  if (ele.children) {
    for (let i = 0; i < ele.children.length; i++) {
      if (ele.children[i].nopath) {
        ele.children.splice(i--, 1)
      }
    }
  }

  if (ele.children) {
    for (let v = 0; v < ele.children.length; v++) {
      if (dataList && dataList.indexOf(ele.children[v].unique) == -1) {
        ele.children.splice(v--, 1)
      }
    }
  }

  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
  const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  // 如果是顶级级路由，并且没有子节点，没有component(自己的页面)  就删除
  if (first && !isChild && !ele.component) {
    return true
  }
  if (isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path].replace(/&/g, "$")
  }

  if (!isChild && first && !isURL(ele[propsDefault.path])) {
    ele[propsDefault.path] = ele[propsDefault.path] + '/index'
  } else {
    ele[propsDefault.children] && ele[propsDefault.children].forEach(child => {
      if (!isURL(child[propsDefault.path])) {
        child[propsDefault.path] = `${ele[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
      }
      addPath(child);
    })
  }
}

const state = {
  userInfo: {},
  permission: [],
  roles: [],
  menuId: getStore({ name: 'menuId' }) || [],
  menu: getStore({ name: 'menu' }) || [],
  menuAll: getStore({ name: 'menuAll' }) || [],
  token: getStore({ name: 'token' }) || '',
}
const actions = {
  //根据用户名登录
  LoginByUsername({ commit }, userInfo) {
    return new Promise((resolve) => {
      loginByUsername(userInfo).then(res => {
        // 由于没有token更新api只能重新静默登录
        setSession('user', btoa(JSON.stringify(userInfo)))
        const data = res.data;
        commit('SET_TOKEN', data);
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        resolve();
      })
    })
  },
  //根据手机号登录
  LoginByPhone({ commit }, userInfo) {
    return new Promise((resolve) => {
      loginByUsername(userInfo.phone, userInfo.code).then(res => {
        const data = res.data;
        commit('SET_TOKEN', data);
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        resolve();
      })
    })
  },
  // 获取用户信息
  GetUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((res) => {
        const data = res.data;
        commit('SET_USERIFNO', data.userInfo);
        commit('SET_ROLES', data.userInfo.roles);
        commit('SET_PERMISSION', data.userInfo.permission)
        resolve(data);
      }).catch(err => {
        reject(err);
      })
    })
  },
  //刷新token
  RefeshToken({ commit }) {
    return new Promise((resolve, reject) => {
      refeshToken().then(res => {
        const data = res.data;
        commit('SET_TOKEN', data);
        resolve(data);
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登出
  LogOut({ commit }) {
    return new Promise((resolve) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_MENUID', {})
        commit('SET_MENUALL', []);
        commit('SET_MENU', [])
        commit('SET_TAG_LIST', [])
        commit('SET_ROLES', [])
        commit('DEL_ALL_TAG');
        commit('CLEAR_LOCK');
        clearSession()
        removeToken()
        resolve()
      })
    })
  },
  //注销session
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_MENUID', {})
      commit('SET_MENUALL', []);
      commit('SET_MENU', [])
      commit('SET_TAG_LIST', [])
      commit('SET_ROLES', [])
      commit('DEL_ALL_TAG');
      commit('CLEAR_LOCK');
      clearSession()
      removeToken()
      resolve()
    })
  },
  //获取系统菜单
  GetMenu({ commit, state }) {
    return new Promise(resolve => {
      const data = menuData
      let menu = deepClone(data);
      if (webiste.permission) {
        // 处理权限
        if (state.roles == webiste.roles) {   //webiste.roles 超级用户 拥有全部权限
          dataList = menuUnique
        } else {
          dataList = state.permission
        }
      } else {
        dataList = menuUnique
      }
      menu.forEach((ele, index) => {
        let temp = addPath(ele, true)
        if (temp) {
          delete menu[index]
        }
      })
      let t  = trimSpace(menu) 
      commit('SET_PERMISSION', dataList)
      commit('SET_MENUALL', t)
      commit('SET_MENU', t)
      resolve(t)
    })
  },
}
const mutations = {
  SET_TOKEN: (state, data) => {
    setToken(data.token, data.tokenExpired)
    state.token = data.token;
    console.log('更新token')
    setStore({ name: 'token', content: state.token })
    setSession('tokentime', (data.tokenExpired - 1000000))

  },
  SET_MENUID(state, menuId) {
    state.menuId = menuId;
    setStore({ name: 'menuId', content: state.menuId, type: 'session' })
  },
  SET_USERIFNO: (state, userInfo) => {
    state.userInfo = userInfo;
    setStore({ name: 'userInfo', content: state.userInfo })
  },
  SET_MENUALL: (state, menuAll) => {
    state.menuAll = menuAll
    setStore({ name: 'menuAll', content: state.menuAll })
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
    setStore({ name: 'menu', content: state.menu })
    if (validatenull(menu)) return
    //合并动态路由去重
    let menuAll = state.menuAll;
    menuAll = menuAll.concat(menu).reverse();
    let newMenu = [];
    for (let item1 of menuAll) {
      let flag = true;
      for (let item2 of newMenu) {
        if (item1.label == item2.label || item1.path == item2.path) {
          flag = false;
        }
      }
      if (flag) newMenu.push(item1);
    }
    state.menuAll = newMenu
    setStore({ name: 'menuAll', content: state.menuAll, type: 'session' })
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission;
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}